const _ = require("lodash");
const uuid = require("uuid/v1");
const router = require("koa-router")();
/**
 *
 * @api {get} /app/config/baseConfig 获取应用基本信息
 *
 */
router.get("/baseConfig", async (ctx, next) => {
  const baas = ctx.baas;
  const userBaas = await BaaS.Models.user_baas
    .query({ where: { baas_id: baas.id } })
    .fetch();
  Object.assign(
    baas,
    { engine: userBaas.engine },
    { charges_id: userBaas.charges_id }
  );
  ctx.success(baas);
});
/**
 *
 * @api {get} /app/config/getKey 获取appkey
 *
 */
router.get("/getKey", async (ctx, next) => {
  const baas = ctx.baas;
  const appkey = uuid();
  // 重置appkey
  ctx.success(appkey);
});
/**
 *
 * @api {post} /app/config/reset 重置应用名称和appkey
 *
 *  * apiParam {String} name 密钥id
 *  * apiParam {String} appkey 密钥id
 *
 */
router.post("/reset", async (ctx, next) => {
  const baas = ctx.baas;
  const { name, appKey } = ctx.post;
  // 判断提交信息是否为空
  const isEmpty = ctx.isEmpty({ name: name, appKey: appKey }, [
    "name",
    "appKey"
  ]);
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }

  const key = `name:${name}:appKey:${appKey}`;
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    // 重置应用名称和appkey
    const result = await BaaS.Models.baas
      .forge({
        id: baas.id,
        name: name,
        appkey: appKey
      })
      .save({
        withRedisKey: `baas:*:appid:${baas.appid}:appkey:${baas.appkey}:baas`
      });
    ctx.success(result);
  } else {
    ctx.error("系统繁忙，请稍后重试");
    console.log(`${key} Waiting`);
    return;
  }
});
/**
 *
 * @api {post} /app/config/switchCharge 切换套餐
 *
 *  * apiParam {Number} chargeId 收费标准id
 *  * apiParam {String} name 应用名称
 *
 */
router.post("/switchCharge", async (ctx, next) => {
  const baas = ctx.baas;
  const { chargeId, name } = ctx.post;
  const chargeS = await BaaS.Models.charges.query({}).fetchAll();
  const chargeIdArr = _.map(chargeS, "id");
  if (chargeIdArr.includes(parseInt(chargeId))) {
    if (baas.name == name) {
      const userBaas = await BaaS.Models.user_baas
        .query({ where: { baas_id: baas.id } })
        .fetch();
      await BaaS.Models.user_baas
        .forge({
          id: userBaas.id,
          charges_id: chargeId,
          engine: 1
        })
        .save();
      ctx.success("修改成功");
    } else {
      ctx.error("输入名称不正确");
    }
  } else {
    ctx.error("修改错误");
  }
});
module.exports = router;
